package com.wulis.provider.basic.web;

import static com.wulis.common.model.enums.VersionEnum.WEB_V_1_0;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.wulis.common.annotation.ApiVersion;
import com.wulis.common.support.BaseController;
import com.wulis.common.wrapper.ApiWrapMapper;
import com.wulis.common.wrapper.ApiWrapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author WuliBao
 * @date 2020-05-21
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("web/basic/file")
@Api(tags = "基础信息管理:文件管理")
public class FileController extends BaseController {

    @ApiVersion(WEB_V_1_0)
    @PostMapping("upload")
    @ApiOperation("文件上传")
    public ApiWrapper<Long> upload(@RequestParam("file") MultipartFile file) {
        return ApiWrapMapper.success(file.getSize());
    }

    @ApiVersion(WEB_V_1_0)
    @PostMapping("download")
    @ApiOperation("文件下载")
    public void download(HttpServletResponse response) throws Exception {
        // TODO 下载后的文件名称
        String fileName = "filename.txt";
        // TODO 文件地址
        File file = new File("E:\\isup.mp4");
        // 相应流类型
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        try (BufferedInputStream inputStream = new BufferedInputStream(Files.newInputStream(file.toPath()));
            OutputStream outputStream = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int index = inputStream.read(buffer);
            while (index != -1) {
                outputStream.write(buffer, 0, buffer.length);
                outputStream.flush();
                index = inputStream.read(buffer);
            }
        } catch (Exception ex) {
            log.error("download error:{}", ex.getMessage());
        }
    }
}
